import fs from 'fs-extra'
import * as cheerio from 'cheerio'
import * as http from 'http'
import * as path from 'path'

function imgUrlToBase64(url : string, callBack : Function) {

    // 解决无法读取https的问题
    url = url.startsWith('https')
        ? url.replace('https', 'http')
        : url

    http.get(url, res => {
        const chunks: any[] = []
        let size = 0

        res.on('data', (chunk : Buffer) => {
            chunks.push(chunk)
            size += chunk.length //累加缓冲数据的长度
        })

        res.on('end', () => {
            const data = Buffer.concat(chunks, size)
            const base64Img = `data:image/${path
                .extname(url)
                .slice(1)};base64,${data
                .toString('base64')}`
            callBack(base64Img)
        })
    })
}

const map = require('../map.json')

const root = path.join(map.root, map.Banners['20240926'])

const htmlFile = path.join(root, 'src/index.html')

// console.log(htmlFile)

interface imgSet {
    [key: string]: string
}
let ist: imgSet = {}

fs.readFile(htmlFile, 'utf8', (err, data) => {

    if (err) 
        console.error('文件读取失败！！！ ' + err)

        // console.log(data.toString());
    
    const $ = cheerio.load(data)

    /* $('img').map((i, e) => {
        console.log(e)
    }) */

    let arr: string[] = []

    $('.layer>video').each((i, e) => console.log($(e).attr('src')))

    $('.layer>img').each((i, e) => {
        let src = $(e).attr('src')

        if (src) 
            arr.push(src)

    })

    loop(arr)

    function loop(arr : string[]) {
        const url = arr.shift()
        if (url) {
            imgUrlToBase64(url, (res : string) => {
                const key = path.basename(url)
                ist[key] = res
                loop(arr)
                // console.log(path.basename(url));

            })

        } else {

            fs.writeFile(path.join(root, 'src/base.json'), JSON.stringify(ist), 'utf8')
            // console.log(imgSet);
        }
    }

})